<!-- eslint-disable @typescript-eslint/no-explicit-any -->
<script setup lang="ts">
  import { NModal, NForm, NFormItem, NInput, NUpload, NSelect, NButton, useMessage } from 'naive-ui'
  import { ref, reactive, onMounted } from 'vue'
  import ModalHeader from '@/components/ModalHeader/index.vue'
  import { uploadFile } from '@/api/common'
  import { createScheme, getKnowledgeList, getModelList } from '@/api/scheme'

  const message = useMessage()
  const showModal = ref(false)
  const emit = defineEmits(['create'])
  const handleOpen = () => {
    showModal.value = true
    clearValidate()
  }

  const handleClose = () => {
    showModal.value = false
  }

  const clearValidate = () => {
    form.name = ''
    form.image = []
    form.desc = ''
    form.knowledgeId = undefined
    form.llmId = undefined
    formRef.value?.restoreValidation()
  }

  const handleBeforeUpload = async ({ file }: any) => {
    // 验证文件大小（2M = 2 * 1024 * 1024 字节）
    const maxSize = 2 * 1024 * 1024 // 2MB

    if (file.file.size > maxSize) {
      message.error('文件大小不能超过2M')
      return false // 阻止上传
    }

    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg']
    if (!allowedTypes.includes(file.file.type)) {
      message.error('只支持 .jpg 和 .png 格式的图片')
      return false // 阻止上传
    }

    const formData = new FormData()
    formData.append('file', file.file)
    formData.append('type', '1') // 普通上传文件存储
    const res = await uploadFile(formData)
    const { fileName, url, objectKey } = res
    form.image = [
      {
        id: objectKey,
        name: fileName,
        status: 'finished',
        url,
      },
    ]
    return true
  }

  const formRef = ref()
  const form = reactive({
    name: '',
    image: [] as any,
    desc: '',
    knowledgeId: undefined,
    llmId: undefined,
  })
  const rules = ref({
    name: { required: true, message: '请输入方案库名称', trigger: 'blur' },
    image: {
      required: true,
      message: '请上传图标',
      validator: (rule: any, value: any) => {
        return new Promise<void>((resolve, reject) => {
          if (value.length === 0) {
            reject(new Error('请上传图标'))
          } else {
            resolve()
          }
        })
      },
    },
    desc: { required: true, message: '请输入方案库介绍', trigger: 'blur' },
    knowledgeId: {
      required: true,
      message: '请选择知识库',
      trigger: ['blur', 'change'],
      validator: (rule: any, value: any) => {
        if (!value) {
          return new Promise<void>((resolve, reject) => {
            reject(new Error('请选择知识库'))
          })
        }
        return new Promise<void>(resolve => {
          resolve()
        })
      },
    },
    llmId: {
      required: true,
      message: '请选择大模型',
      trigger: ['blur', 'change'],
      validator: (rule: any, value: any) => {
        if (!value) {
          return new Promise<void>((resolve, reject) => {
            reject(new Error('请选择大模型'))
          })
        }
        return new Promise<void>(resolve => {
          resolve()
        })
      },
    },
  })

  const handleSubmit = async () => {
    formRef.value?.validate(async (errors: any) => {
      if (!errors) {
        console.log('验证通过')
        const data = {
          name: form.name,
          description: form.desc,
          knowledgeId: form.knowledgeId ?? undefined,
          llmId: form.llmId ?? undefined,
          url: form.image[0].url,
        }
        await createScheme(data)
        handleClose()
        emit('create', form.name)
      } else {
        console.log(errors)
      }
    })
  }

  const knowledgeList = ref([])
  const modelList = ref([])

  const getKnowledgeListFn = async () => {
    const res = await getKnowledgeList()
    console.log(res)
    knowledgeList.value = res
  }

  const getModelListFn = async () => {
    const res = await getModelList()
    modelList.value = res
  }

  onMounted(async () => {
    await getKnowledgeListFn()
    await getModelListFn()
  })

  defineExpose({
    handleOpen,
  })
</script>

<template>
  <n-modal
    style="width: 528px"
    :bordered="false"
    role="dialog"
    aria-modal="true"
    v-model:show="showModal"
    transform-origin="center"
    @close="handleClose"
  >
    <div class="w-full h-full flex flex-col bg-white rounded pingfang">
      <ModalHeader title="新建方案库" @close="handleClose" />
      <n-form
        class="flex-1 px-5"
        ref="formRef"
        :model="form"
        :rules="rules"
        require-mark-placement="left"
      >
        <n-form-item label="名称" path="name">
          <n-input
            v-model:value="form.name"
            maxlength="40"
            show-count
            placeholder="请输入方案库名称"
          />
        </n-form-item>
        <n-form-item label="图标" path="image" required>
          <div class="flex flex-col">
            <n-upload
              accept=".jpg,.png"
              :on-before-upload="handleBeforeUpload"
              :default-file-list="form.image"
              list-type="image-card"
              :max="1"
            >
            </n-upload>
            <div class="text-[#A3A7AD]">文件类型：.jpg，.png，大小2M以内</div>
          </div>
        </n-form-item>
        <n-form-item label="介绍" path="desc" required>
          <n-input
            v-model:value="form.desc"
            maxlength="300"
            show-count
            :autosize="{ minRows: 3, maxRows: 3 }"
            type="textarea"
            placeholder="请输入方案库介绍"
          />
        </n-form-item>
        <n-form-item label="知识库" path="knowledgeId">
          <n-select
            v-model:value="form.knowledgeId"
            placeholder="请选择知识库"
            :options="
              knowledgeList.map((item: any) => {
                return {
                  label: item.name,
                  value: item.id,
                }
              })
            "
          />
        </n-form-item>
        <n-form-item label="大模型" path="llmId">
          <n-select
            v-model:value="form.llmId"
            placeholder="请选择大模型"
            :options="
              modelList.map((item: any) => {
                return {
                  label: item.name,
                  value: item.id,
                }
              })
            "
          />
        </n-form-item>
      </n-form>
      <div class="flex justify-end px-5 py-4">
        <n-button class="w-[60px] mr-4 text-[#4A5055]" @click="handleClose"> 取消 </n-button>
        <n-button type="primary" class="w-[60px]" @click="handleSubmit"> 确认 </n-button>
      </div>
    </div>
  </n-modal>
</template>
